﻿using System;
using System.Collections.Generic;
using ku.datamodel.contract;
using System.Linq;

namespace ku.tokenizer
{
    public class Tokenizer : ku.tokenizer.contract.ITokenizer
    {
        public IEnumerable<Token> Tokenize(string text)
        {

            List<Token> TokenList = new List<Token>();

            if (text != "")
            {
                string TempTokenInhalt = "";
                TokenType TempTokenType = TokenType.Wort;

                foreach (var Character in text.ToCharArray())
                {
                    if (TempTokenInhalt == "")
                    {
                        TempTokenInhalt += Character;
                        TempTokenType = GetTokenType(Character);
                    }
                    else
                    {
                        if (TempTokenType == TokenType.Wort && GetTokenType(Character) == TokenType.Wort)
                        {
                            TempTokenInhalt = TempTokenInhalt + Character;
                        }
                        else
                        {
                            TokenList.Add(new Token(TempTokenInhalt, TempTokenType));
                            TempTokenInhalt = Character.ToString();
                            TempTokenType = GetTokenType(Character);
                        }
                    }
                }

                TokenList.Add(new Token(TempTokenInhalt, TempTokenType));
            }
            TokenList.Add(new Token("", TokenType.Textende));

            return TokenList.ToArray();
        }

        internal TokenType GetTokenType(char Character)
        {
            if(char.IsLetter(Character))
            {
                return TokenType.Wort;
            }

            if(Character == ' ')
            {
                return TokenType.Whitespace;
            }

            if (Character == '.' || Character == ',' || Character == '!' || Character == '?' || Character == ';'  || Character == '-' || Character == '\'')
            {
                return TokenType.Satzzeichen;
            }

            if (Convert.ToInt32(Character) == 13)
            {
                return TokenType.Whitespace;
            }

            if (Convert.ToInt32(Character) == 10)
            {
                return TokenType.Wort;
            }

            throw new Exception("'" + Character + "' (" + Convert.ToInt32(Character) + ") --> TokenType cannot be found!");
        }
    }
}
